<?php
class StoriesController extends AppController {

	var $name = 'Stories';
	var $helpers = array('Html', 'Form');


	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid story.', true));
			$this->redirect('/');
		}
		$user = $this->Auth->user();
		
		
		
		$this->Story->recursive = 3;
		$this->Story->unbindModel(array('hasMany' => array('Post')));
		$this->Story->Image->unbindModel(array('belongsTo' => array('Story', 'Profile')));
		$this->Story->User->unbindModel(array('hasAndBelongsToMany' => array('Friend')));
		$this->Story->City->unbindModel(array('hasMany' => array( 'Profile', 'Post')));
		$this->Story->City->Country->unbindModel(array('hasMany' => array('City', 'Region')));
		$this->Story->City->Region->unbindModel(array('hasMany' => array('City')));
		$this->Story->City->Region->unbindModel(array('belongsTo' => array('Country')));
		
		
		$story = $this->Story->findById($id);
		shuffle($story['Image']);
		
		if(!isset($story['Story']['id']))
		 $this->cakeError('error404');
		
		/* are the story author and the user friends */
		$friends = $this->Story->User->Friend->find('all',
    		array('conditions' =>  
    						array('OR' => 
    							array(
    								array('Friend.user_id' => $user['User']['id'], 'Friend.friend_id' => $story['User']['id']),
    								array('Friend.user_id' => $story['User']['id'], 'Friend.friend_id' => $user['User']['id'])
    								))
    			 		
    			 ));
    			
    	$this->set('isFriend',!empty($friends));
		
    	/* am I the story author */
		$this->set('isMe', ($story['User']['id'] == $user['User']['id']));
		
		$this->set('story',$story);
		//debug($story);
		
		$this->Story->Post->recursive = 3;
		$this->Story->Post->unbindModel(array('belongsTo' => array('City','Profile', 'Story')));
		$this->Story->Post->User->unbindModel(array('hasMany' => array('Story')));
		$this->Story->Post->User->Profile->unbindModel(array('hasMany' => array('Post'), 'belongsTo' => array('User')));
		$this->Story->Post->User->unbindModel(array('hasAndBelongsToMany' => array('Friend')));
		$posts = $this->Story->Post->find('all', array('conditions' => array('Post.story_id' => $id), 'order' => 'Post.created DESC'));
		$this->set('posts',$posts);
	
		$this->set('user', $user);
		//$this->set('story', $this->Story->read(null, $id));
	}

	function add($city_id=null,$latitude=null,$longitude=null) {
		
		if (!empty($this->data)) {
			$user = $this->Auth->user();
			$user_id = $user['User']['id'];

			// add user id to story
			$this->data['Story']['user_id'] = $user_id;
			
			if(strlen($this->data['Story']['message']) > 10000)
		     $this->data['Story']['message'] = substr($this->data['Story']['message'],0,10000) . '...truncated due to length.';
			
			
			
			$this->Story->set($this->data);
			if($this->Story->validates())
			{
					$formError = false;
			}
			else
			{
					$formError = true;
      				//$errors = $this->Story->invalidFields();
      				//$this->Session->setFlash(implode('', $errors));  
      				//$this->render();
      				//exit();
			}
			
			
			foreach($this->data['Story'] as $key => &$val)
			{
				$patterns = array( "/</", "/>/",);
			    $replacements = array( "&lt;", "&gt;");
				$val = preg_replace($patterns, $replacements, $val);
			}
			
			if(!$formError)
				$this->Story->create();
			
			if (!$formError && $this->Story->save($this->data)) {
				$this->Session->setFlash(__('The story has been saved.', true));
				$this->redirect(array('controller' => 'stories', 'action'=>'view', $this->Story->id));
			} else {	
				$this->Session->setFlash(__('The story could not be saved.', true));
				
				
			}
		}
		else
		{
			if($city_id == null || $latitude == null || $longitude == null)
			 $this->redirect(Controller::referer());
			 
			$this->data['Story']['latitude'] = $latitude;
			$this->data['Story']['longitude'] = $longitude;
			$this->data['Story']['city_id'] = $city_id;
			
			foreach($this->data['Story'] as $key => &$val)
			{
				$patterns = array( "/</", "/>/",);
			    $replacements = array( "&lt;", "&gt;");
				$val = preg_replace($patterns, $replacements, $val);
			}	
		}
		
		//debug($this->data);
		
		$this->Story->City->recursive = 1;
		$this->Story->City->unbindModel(array('hasMany' => array('Story','Profile','Post')));
		//$this->Story->City->unbindModel(array('hasAndBelongsToMany' => array('Visited')));
		$city = $this->Story->City->findById($this->data['Story']['city_id']);
		
		$outOfRange = false;
		
		if(abs($city['City']['latitude'] - $this->data['Story']['latitude']) > 0.5 ||
		   abs($city['City']['longitude'] - $this->data['Story']['longitude']) > 0.5)
			 $outOfRange = true;
		
		if($outOfRange)
		{
			$this->Session->setFlash(__('Too far away to add story.', true));
			$this->redirect(array('controller' => 'cities', 'action' => 'view', $city['City']['id']));
		}
		$this->set('city',$city);
		$this->Story->set($this->data);
		$this->set('latitude',$this->data['Story']['latitude']);
		$this->set('longitude', $this->data['Story']['longitude']);
		
		if($formError)
		 $errors = $this->Story->invalidFields();
	}

	function beforeFilter() {
		$this->Session->write('Auth.redirect', $this->here);
		$this->Auth->allow('index', 'view');
	}

}
?>